<template>
    <div class="container container-addDemand">
        <a-modal width="1300px" :visible="visible" title="编辑需求" class="yuan-modal demand-add-modal"
            :dialog-style="{ top: '20px' }" @cancel="closeModal">
            <div class="page-panell">
                <div class="panel-title">
                    <div class="panel-content">我的需求</div>
                </div>
            </div>
            <a-spin tip="Loading..." :spinning="formLoading">
                <a-form-model layout="inline" class="yuan-form panel-content" v-if="!isAdd">
                    <div class="form-panel">
                        <a-form-model-item class="yuan-form-row" label="是否从已有需求方案导入" :label-col="{ style: { width: '170px' } }"
                            :wrapper-col="{ style: { width: 'calc(100% - 170px)' } }">
                            <a-radio-group v-model="pageType" @change="pageTypeChange">
                                <a-radio :value="1">否</a-radio>
                                <a-radio :value="2">
                                    <span>是</span>
                                    <span v-if="pageType===2">: </span>
                                    <a-select style="width:200px" class="yuan-form-input" v-model="selectMyAchId"
                                        placeholder="请选择方案" v-if="pageType===2" @change="selectMyAch">

                                        <a-select-option :value="item.id" v-for="item in myAchList"
                                            :key="item.id">{{item.demandName}}</a-select-option>
                                    </a-select>

                                </a-radio>

                            </a-radio-group>
                        </a-form-model-item>
                    </div>
                </a-form-model>
                <a-form-model layout="inline" class="yuan-form panel-content" :label-col="{ style: { width: '160px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }" ref="form" :model="formData" :rules="rules"
                    :class="pageType===2?'disable-form':''">
                    <div class="form-panel">
                        <div v-show="!isNext">
                            <a-form-model-item label="封面图" class="yuan-form-item" v-if="pageReady">
                                <UploadVue :uploadLength="1" @uploadChange="uploadChangeCoverImageUrl"
                                    :defImgList="formData.coverImageUrl?[formData.coverImageUrl]:[]" />
                                <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="需求名称" prop="demandName">
                                <a-input class="yuan-form-input" v-model="formData.demandName" placeholder="请输入"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="技术简介" prop="technicalDescription">
                                <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                    v-model="formData.technicalDescription" placeholder="请输入简介" :maxLength="1000" />
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-row" label="分类" prop="category">
                                <a-radio-group v-model="formData.category">
                                    <a-radio value="生产研发需求">生产研发需求</a-radio>
                                    <a-radio value="技术服务需求">技术服务需求</a-radio>
                                    <a-radio value="临床效果需求">临床效果需求</a-radio>
                                    <a-radio value="生产技术需求">生产技术需求</a-radio>
                                    <a-radio value="其他">
                                        <span>其他：</span>
                                        <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                            v-model="formData.categoryOther" :maxNum="15" placeholder="请输入" />
                                    </a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="细分领域" prop="subCategory">
                                <a-checkbox-group v-model="formData.subCategory">
                                    <a-checkbox :value="item.content" v-for="item in territoryList"
                                        :key="item.id">{{item.content}}</a-checkbox>
                                    <a-checkbox value="其他">
                                        <span>其他：</span>
                                        <CountInputVue style="margin-left:5px" class="yuan-form-input"
                                            v-model="formData.subCategoryOther" :maxNum="15" placeholder="请输入" />
                                    </a-checkbox>
                                </a-checkbox-group>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-row" label="企业/单位名称" prop="companyName">
                                <a-input class="yuan-form-input" v-model="formData.companyName" placeholder="请输入"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="联系人" prop="contacts">
                                <a-input class="yuan-form-input" v-model="formData.contacts" placeholder="请输入"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="联系方式" prop="contactInfo">
                                <a-input class="yuan-form-input" v-model="formData.contactInfo" placeholder="请输入"></a-input>
                            </a-form-model-item>
                        </div>
                        <div v-show="isNext">
                            <a-form-model-item class="yuan-form-row" label="拟投入金额" prop="investmentMin">
                                <a-input class="yuan-form-input" v-model="formData.investmentMin" placeholder="请输入"></a-input>
                                <span>~</span>
                                <a-input class="yuan-form-input" v-model="formData.investmentMax" placeholder="请输入"></a-input>
                                <span> 万元</span>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item yuan-form-col5" label="需求截止时间" prop="deadline">
                                <a-date-picker class="yuan-form-input" placeholder="需求截止时间" v-model="formData.deadline"
                                    inputReadOnly valueFormat="YYYY-MM-DD" @change="deadlineChange" />
                                <span v-show="formData.deadline"> 
                                    剩余天数：{{formData.residueDay>=0?formData.residueDay+'天':'已过期'}}
                                </span>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="需求发布地址" prop="placeAreaCode">
                                <a-cascader class="yuan-form-input" :options="addrData" v-model="formData.placeAreaCode"
                                    placeholder="请选择" @change="onAddrChange" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="授权经纪人">

                                <div v-for="(item,idx) in formData.brokerRelevances">
                                    <span style="display:inline-block;width:200px;;border-bottom: solid 1px #eee;">{{item.technicalRepresentative}}</span>
                                    <a-button type="danger" @click="delUser(idx)">移除</a-button>
                                </div>
                                <div></div>
                                <a-button type="primary" @click="()=>userVisible=true">选择技术经纪人</a-button>

                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="需求描述" prop="synopsis">
                                <div class="editor" style="min-height:300px;width:1000px">
                                    <Toolbar style="border-bottom: 1px solid #ccc;" :editor="editorRef"
                                        :defaultConfig="editorConfig.toolbarConfig" mode="default" />
                                    <Editor v-model="formData.synopsis" :defaultConfig="editorConfig" mode="default"
                                        @onCreated="handleCreated" />
                                </div>
                            </a-form-model-item>

                        </div>

                    </div>
                </a-form-model>
            </a-spin>
            <template slot="footer">
                <a-button @click="isNext=true" type="warning" :loading="formLoading" v-if="!isNext">
                    下一步
                </a-button>
                <a-button @click="isNext=false" type="warning" :loading="formLoading" v-else>
                    上一步
                </a-button>
                <a-button @click="save" type="primary" :loading="formLoading" v-if="isNext">
                    提交
                </a-button>
                <a-button @click="closeModal">
                    取消
                </a-button>
            </template>
        </a-modal>
        <a-modal title="提示" :visible="tipsVisible" :confirm-loading="formLoading" @ok="onOk" @cancel="closeTipsModal" okText="确定"
            cancelText="取消">
            <div v-if="!isAdd">
                您的需求需要递交到平台进行审核，在平台审核通过会自动投递到该成果，您可以在工作台-需求管理查看投递进度。
            </div>
            <div v-else>
                您的需求需要递交到平台进行审核，您可以在工作台-需求管理查看投递进度。
            </div>
            <div>
                是否投递该需求？
            </div>
        </a-modal>

        <UserVue :visible="userVisible" @closeModal="() => userVisible = false" @sureClose="selectUser" />
    </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
import CountInputVue from "@/components/countInput.vue";
import areaJson, { getAreaWords } from "@/utils/area";
import UserVue from "@/components/addUserModal.vue";
import api from "@/api/api";
import UploadVue from "@/components/upload.vue";
import { MENU_CONF, toolbarConfig } from "@/utils/wangeditors";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
@Component({
    name: "dom",
    components: { CountInputVue, UserVue, UploadVue, Editor, Toolbar },
})
export default class index extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: false }) isAdd!: boolean;
    @Prop({ default: "" }) achId!: string;
    tipsVisible = false;
    formLoading = false;
    pageType = 1;
    formData: any = {
        brokerRelevances:[]
    };
    pageReady = false;
    isNext = false;
    rules = {
        demandName: [{ required: true, message: "请输入需求名称", trigger: "change" }],
        technicalDescription: [{ required: true, message: "请输入描述", trigger: "change" }],
        category: [{ required: true, message: "请选择分类", trigger: "change" }],
        subCategory: [{ required: true, message: "请选择细分领域", trigger: "change" }],
        // investmentMin: [{ required: true, message: "请填写投入金额", trigger: "change" }],
        companyName: [{ required: true, message: "请填写企业单位名称", trigger: "change" }],
        contacts: [{ required: true, message: "请填写联系人", trigger: "change" }],
        contactInfo: [{ required: true, message: "请填写联系方式", trigger: "change" }],
        synopsis: [{ required: true, message: "请填写需求描述", trigger: "change" }],
        // deadline: [{ required: true, message: "请选择截至时间", trigger: "change" }],
        // placeAreaCode: [{ required: true, message: "请选择发布地址", trigger: "change" }],
        // hasTechnicalRepresentative: [{ required: true, message: "请选择技术经纪人", trigger: "change" }],
    };

    closeModal() {
        this.$emit("closeModal");
    }
    closeTipsModal() {
        this.tipsVisible = false;
    }
    save() {
        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!this.formData.synopsis) {
                this.$message.error("请填写需求描述");
                return;
            }
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            
            this.tipsVisible = true;
        });
    }

    otherArr = ["category", "subCategory"];
    onOk() {
        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            this.formLoading = true;
            try {
                let data;
                if (this.isAdd) {
                    //新增
                    data = {
                        ...this.formData,
                        sign:'前台',
                        ifDeliver: 0,
                    };
                } else if (this.pageType === 1) {
                    // 如果不是导入
                    data = {
                        ...this.formData,
                        hasTechnicalRepresentative: this.formData.technicalRepresentative ? 1 : 0,
                        ifDeliver: 1,
                        achievementId: this.achId,
                        //achievementDifferentiate: this.formData.demandType,
                    };
                } else {
                    data = {
                        ...this.formData,
                        ifDeliver: 0,
                        achievementId: this.achId,
                    };
                }

                this.otherArr.forEach((item) => {
                    if (typeof data[item] === "string") {
                        if (data[item] === "其他") {
                            data[item] = "其他-" + (data[item + "Other"] || "");
                        }
                    } else if (typeof data[item] === "object") {
                        data[item] = data[item].map((child) => {
                            if (child === "其他") {
                                return "其他-" + (data[item + "Other"] || "");
                            } else {
                                return child;
                            }
                        });
                    }
                });
                if (this.isAdd) {
                    const res = await api.addDemandNew(data);
                } else {
                    const res = await api.addDemand(data);
                }

                this.$message.success("保存成功,您可以在工作台查看对接进度");
                this.formData = {brokerRelevances:[]};
                this.pageReady = false;
                this.$nextTick(() => {
                    this.pageReady = true;
                });
                this.tipsVisible = false;
                this.closeModal();
            } finally {
                this.formLoading = false;
            }
        });
    }
    mounted() {
        
        this.setAddrData();
        this.formLoading = true;
        Promise.all([this.getTerritoryList(), this.getMyAch()]).then(() => {
            //
            this.pageReady = true;
            this.formLoading = false;
        });
    }

    territoryList = [];
    async getTerritoryList() {
        try {
            const res = await api.getSetting("3");
            this.territoryList = res.data;
        } finally {
            //
        }
    }

    userVisible = false;
    selectUser(userInfo) {
        if (this.formData.brokerRelevances) {
            this.formData.brokerRelevances.push({
                technicalRepresentative: userInfo.name,
                technicalHeadPortrait: userInfo.headPortrait,
                technicalPhone: userInfo.phone,
            });
        } else {
            this.formData.brokerRelevances = [
                {
                    technicalRepresentative: userInfo.name,
                    technicalHeadPortrait: userInfo.headPortrait,
                    technicalPhone: userInfo.phone,
                },
            ];
        }
    }
    myAchList: any[] = [];
    async getMyAch() {
        if (this.isAdd) return;
        try {
            const res = await api.getMyDemand();
            this.myAchList = res.data;
        } finally {
            //
        }
    }
    selectMyAchId = "";
    selectMyAch() {
        this.pageReady = false;
        const find = this.myAchList.find((item) => item.id === this.selectMyAchId);
        if (find) {
            // find.applicationIndustry = find.applicationIndustry ? JSON.parse(find.applicationIndustry) : [];
            // find.belongToTechnologyCategory = find.belongToTechnologyCategory ? JSON.parse(find.belongToTechnologyCategory) : [];
            // find.embodyForm = find.embodyForm ? JSON.parse(find.embodyForm) : [];
            // find.promotionForm = find.promotionForm ? JSON.parse(find.promotionForm) : [];
            if (find.subCategory) {
                find.subCategory = typeof find.subCategory === "string" ? JSON.parse(find.subCategory) : find.subCategory;
            }
            if (find.code) {
                find.placeAreaCode = find.code.split(",");
            }
            if (find.location) {
                find.location = typeof find.location === "string" ? JSON.parse(find.location) : find.location;
            }
            if (find.introImageUrl) {
                find.introImageUrl =
                    typeof find.introImageUrl === "string" ? JSON.parse(find.introImageUrl) : find.introImageUrl;
            }
        }
        this.formData = { ...find };
        this.$nextTick(() => {
            this.pageReady = true;
        });
    }

    pageTypeChange() {
        this.pageReady = false;
        this.formData = {};
        this.selectMyAchId = "";
        this.$nextTick(() => {
            this.pageReady = true;
        });
    }

    uploadChangeCoverImageUrl(e) {
        this.formData.coverImageUrl = e.length ? e[0].url : "";
    }

    addrData: any[] = [];
    setAddrData() {
        this.addrData = areaJson;
    }
    onAddrChange(e: any) {
        this.formData.code = e.join(",");
        this.formData.location = getAreaWords(e);
    }

    deadlineChange() {
        if (!this.formData.deadline) return "";
        const nowTime = new Date().getTime();
        const deadlineTime = new Date(this.formData.deadline.replace(/-/g, "/")).getTime();
        const day = (deadlineTime - nowTime) / (24 * 60 * 60 * 1000);
        this.formData.deadlineDay = Math.ceil(day);
    }
    editorRef = null;
    editorConfig = {
        placeholder: "请输入内容...",
        //配置工具栏
        toolbarConfig: toolbarConfig,
        MENU_CONF: MENU_CONF,
    };
    handleCreated(editor) {
        this.editorRef = editor; // 记录 editor 实例
    }

    delUser(idx) {
        this.formData.brokerRelevances.splice(idx, 1);
        console.info(this.formData)
    }
}
</script>

<style lang="scss">
.demand-add-modal {
    .panel-content {
        width: 100%;
    }
    .panel-title {
        font-weight: bold;
        font-size: 22px;
        color: #2f65f3;
        background-color: #fff;

        .panel-content {
            height: 40px;
            display: flex;
            align-items: center;
        }
        .panel-content::before {
            content: "";
            display: inline-block;
            height: 26px;
            width: 1px;
            border-right: 3px solid #2f65f3;
            margin-right: 20px;
        }
    }
    .yuan-form {
        background-color: #fff;
        margin-top: 15px;
        padding: 20px;
    }
    .bottom-btn-box {
        text-align: center;
        padding: 50px;
    }
    .bottom-btn {
        height: 40px;
        width: 120px;
        font-size: 14px;
    }
    .yuan-form-row {
        margin-bottom: 20px;
        
        .ant-checkbox-wrapper,.ant-radio-wrapper{
            line-height: 40px;
        }
    }
    .disable-form {
        pointer-events: none;
    }
}
</style>
